﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using NetWork.Packets.Factory;
using NetWork.Packets;

namespace NetWork.Layer
{
    public class WWWHttpUtil : MonoBehaviour
    {
        private static WWWHttpUtil instance;
        public static WWWHttpUtil Instance
        {
            get
            {
                return instance;
            }
        }
        void Awake()
        {
            instance = this;
        }
        public void Send(int id, object pbData, HttpHandler successHandler)
        {
            byte[] msg;
            if (PacketFactory.WebPB2Bytes(id, pbData, out msg))
            {
                StartCoroutine( SendAsync(msg, successHandler));
            }
            else
            {
                Debug.LogError("message trans error");
            }
        }

        private IEnumerator SendAsync(byte[] msg,HttpHandler handler)
        {
            WWW www = new WWW(/**/StaticData.httpServer /*"http://192.168.1.5/sao" */, msg);
            yield return www;
            if(www.error != null)
            {
                //if(www.error.EndsWith(" Timed out"))
                //{

                //}
                handler(null, false);
                Debug.LogError("Net Exception " + www.error);
            }
            else
            {
                if (handler == null)
                {
                    yield break;
                }
                byte[] bs = www.bytes;
                int id;
                object pbData;
                List<Packet> externalPacks;
                if (PacketFactory.WebBytes2PB(bs, out id, out pbData,out externalPacks))
                {
#if UNITY_EDITOR
                    UnityEngine.Debug.LogWarning("Packet size is " + bs.Length);
#endif
                    Packet p = new Packet(id,pbData);
                    if(id == ProtoBuf.Message.OpDefine.ErrorMessage)
                    {
                        handler(p, false);
                    }
                    else
                    {
                        handler(p, true);
                    }
                }
                else
                {
                    Debug.LogError("message translate error !");
                    handler(null, false);
                }
            }
        }

        public void StopAll()
        {
            StopAllCoroutines();
        }
    }
}